﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DLULearningNetwork.Libs;
using DLULearningNetworkModel;
using DLULearningNetwork.ActionFilterAttributes;
using DLULearningNetwork.ViewModels;

namespace DLULearningNetwork.Controllers
{

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            if (LibSession.Get(Constants.ACCOUNT_LOGIN) != null)
            {
                return RedirectToAction("HomePage", "Home");
            }
            else
            {
                string email = LibCookie.Get(Constants.EMAIL_LOGIN);
                string password = LibCookie.Get(Constants.PASSWORD_LOGIN);
                Account acc = Account.Single(email, StringHelper.EncodeMD5(password));
                if (acc != null)
                {
                    LibSession.Set(Constants.ACCOUNT_LOGIN, acc);
                    return RedirectToAction("HomePage", "Home");
                }
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection frm)
        {
            string email = frm["Email_Login"];
            string password = frm["Password_Login"];
            Account acc = Account.Single(email, StringHelper.EncodeMD5(password));
            if (acc == null)
            {
                return RedirectToAction("Login", "Account");
            }
            if (acc.IsBanned_b != null && acc.IsBanned_b == true)
            {
                return PartialView("ErrorMessage", "Tài khoản này đã bị cấm sử dụng, liên hệ với nhà quản trị để biết thêm thông tin");
            }
            LibSession.Set(Constants.ACCOUNT_LOGIN, acc);
            if (frm["KeepLogin"] != null)
            {
                LibCookie.Add(Constants.EMAIL_LOGIN, email, DateTime.Now.AddDays(20));
                LibCookie.Add(Constants.PASSWORD_LOGIN, password, DateTime.Now.AddDays(20));
            }

            return RedirectToAction("HomePage", "Home");
        }

        [RequireUserLogin()]
        public ActionResult HomePage()
        {
            ViewBag.ActiveMenus = new List<string>{LeftMainMenuItem.EnumLeftMenuItem.HomePage.ToString()
            };
            return View();
        }

        [HttpPost]
        [RequireUserLogin()]
        public ActionResult AddNewPost(string content)
        {
            if (StringHelper.GetLengthOfContent(content) < 1)
            {
                return PartialView("ErrorMessage", "unsuccess/0");
            }
            if (StringHelper.GetLengthOfContent(content) > 5000)
            {
                return PartialView("ErrorMessage", "unsuccess/1");
            }
            
            //Khong kiem tra quyen vi khi user dang nhap goi ham nay chi tac dong len thong tin cua chinh user
            Account currentUser = RequireUserLogin.LoginUser;
            //Them feed 
            Feed newFeed = new Feed();
            newFeed.FeedID_u = Guid.NewGuid();
            newFeed.ActiveAccountID_u = currentUser.AccountID_u;
            newFeed.PassiveAccountID_u = currentUser.AccountID_u;
            newFeed.Content_s = HttpUtility.HtmlDecode(content);
            newFeed.CreateDate_dt = DateTime.Now;
            newFeed.LastUpdate_dt = DateTime.Now;
            newFeed.Type_s = EnumFeedType.PostOnWall.ToString();
            if (Feed.Add(newFeed) == 1)
            {
                newFeed = Feed.SelectByFeedID(newFeed.FeedID_u);
                if (newFeed != null)
                {
                    //Undone : Add Feed for friend ban cua
                    int i = FeedForFriend.AddFeedForFriend(newFeed.FeedID_u, currentUser.AccountID_u);
                    // tra ve html cua feed do
                    ViewBag.AllowComment = true;
                    return PartialView("Feed", newFeed);
                }
            }
            return PartialView("ErrorMessage", "unsuccess");
        }

        [RequireUserLogin()]
        [HttpPost]
        public ActionResult AddNewComment(string feedID, string content)
        {
            if (StringHelper.GetLengthOfContent(content) < 1)
            {
                return PartialView("ErrorMessage", "unsuccess/0");
            }
            if (StringHelper.GetLengthOfContent(content) > 5000)
            {
                return PartialView("ErrorMessage", "unsuccess/1");
            }
            Feed feed = Feed.SelectByFeedID(Guid.Parse(feedID));
            Account currentUser = RequireUserLogin.LoginUser;
            if (feed != null)
            {
                if (feed.ActiveAccountID_u != currentUser.AccountID_u)
                {
                    if (feed.Type_s == EnumFeedType.PostOnCourseWall.ToString())
                    {
                        
                        Course course = Course.Single(currentUser.AccountID_u);
                        //không phải ngưởi mở lớp học
                        if (course == null)
                        {
                            //kiem tra co enroll khong
                            Enrollment enroll = Enrollment.Single(currentUser.AccountID_u, feed.CourseID_u.Value);
                            if (enroll == null || enroll.Status_i !=1)
                            {
                                return PartialView("ErrorMessage", "unsuccess");
                            }
                        }
                    }
                    else
                    {
                        if (feed.Type_s == EnumFeedType.PostOnWall.ToString())
                        {
                            if (feed.PassiveAccountID_u != currentUser.AccountID_u)
                            {
                                Friend friendship = Friend.Single(currentUser.AccountID_u, feed.PassiveAccountID_u.Value);
                                if (friendship == null)
                                {
                                    return PartialView("ErrorMessage", "unsuccess");
                                }
                            }
                        }
                        else// khong the comment tren cac feed khac post
                        {
                            return PartialView("ErrorMessage", "unsuccess");
                        }
                    }
                }
                FeedComment fcmt = new FeedComment();
                fcmt.ActiveAccount_u = currentUser.AccountID_u;
                fcmt.FeedCommentID_u = Guid.NewGuid();
                fcmt.Content_s = HttpUtility.HtmlDecode(content);
                fcmt.FeedID_u = feed.FeedID_u;
                fcmt.CreateDate_dt = DateTime.Now;
                if (FeedComment.Add(fcmt) == 1)
                {
                    fcmt = FeedComment.SelectByFeedCommentID(fcmt.FeedCommentID_u);
                    if (fcmt != null)
                    {
                        //Cap nhat lai lastupdate cua feed
                        Feed.UpdateLastDate(Guid.Parse(feedID));
                        //Neu binh luan feed cua chinh minh thi khong can tao feed hoat dong gan day, Tao feed binh luan hoat dong gan day, binh luan gi do....
                        //Feed la hoat dong binh luan gan day thi khong thong bao voi ban be (khong can tao feed forFriend)
                        if (feed.PassiveAccountID_u != currentUser.AccountID_u)
                        {
                            Feed newFeed = new Feed();
                            newFeed.FeedID_u = Guid.NewGuid();
                            newFeed.ActiveAccountID_u = currentUser.AccountID_u;
                            newFeed.Type_s = EnumFeedType.ActivityComment.ToString();
                            newFeed.CreateDate_dt = DateTime.Now;
                            newFeed.LastUpdate_dt = DateTime.Now;
                            newFeed.CommentID = fcmt.FeedCommentID_u;
                            newFeed.Content_s = StringHelper.ShortcutContent(content, 30);
                            //Undone : transaction
                            Feed.Add(newFeed);
                        }
                        return PartialView("FeedComment", fcmt);
                    }
                }
            }
            return PartialView("ErrorMessage", "unsuccess");
        }

        [RequireUserLogin()]
        public ActionResult GetListFeed(int numberOfSkip)
        {
            Account currentUser = RequireUserLogin.LoginUser;
            //Lay lan luot feed ma ban be cia minh tao ra  trong feedforfriend
            List<FeedForFriend> lstFeedForFriend = FeedForFriend.SelectFeedForFriendOfAccount(currentUser.AccountID_u, numberOfSkip, Constants.DEFAULT_NUMBER_OF_FEED);
            List<Feed> lstFeed = (from fff in lstFeedForFriend
                                  select fff.FeedReference.Value).ToList();
            ViewBag.AllowComment = true;
            ViewBag.AllowDelete = true;
            return PartialView("ListFeed", lstFeed);
        }

        [RequireUserLogin()]
        public ActionResult GetLatestFeed()
        {
            Account currentUser = RequireUserLogin.LoginUser;
            //Lay lan luot feed ma ban be cia minh tao ra  trong feedforfriend
            object temp = LibSession.Get(Constants.LASTTIME_GET_LATEST_FEED);
            DateTime time;
            if (temp == null)
            {
                 time = DateTime.Now;
            }
            else
            {
                time = DateTime.Parse(temp.ToString());
            }
            LibSession.Set(Constants.LASTTIME_GET_LATEST_FEED,DateTime.Now);
            List<FeedForFriend> lstFeedForFriend = FeedForFriend.SelectLatestFeedForFriendOfAccount(currentUser.AccountID_u, time);
            List<Feed> lstFeed = (from fff in lstFeedForFriend
                                  select fff.FeedReference.Value).ToList();
            ViewBag.AllowComment = true;
            ViewBag.AllowDelete = true;
            return PartialView("ListFeed", lstFeed);
        }

        [RequireUserLogin()]
        [HttpGet]
        public ActionResult GetListFeedComment(string feedID, int numberOfSkip)
        {
            List<FeedComment> lstFeedComment = FeedComment.SelectByFeedID(Guid.Parse(feedID), numberOfSkip, Constants.DEFAULT_NUMBER_OF_FEEDCOMMENT);
            lstFeedComment = lstFeedComment.OrderBy(fc => fc.CreateDate_dt).ToList();
            return PartialView("ListFeedComment", lstFeedComment);
        }

        [RequireUserLogin]
        [HttpPost]
        public string DeleteFeed(string feedID)
        {
            Feed existingFeed = Feed.SelectByFeedID(Guid.Parse(feedID));
            Account currentUser = RequireUserLogin.LoginUser;
            if (existingFeed != null)
            {
                if (existingFeed.ActiveAccountID_u == currentUser.AccountID_u // tao ra feed
                    || (existingFeed.CourseReference.Value != null && existingFeed.CourseReference.Value.AccountID_u == currentUser.AccountID_u)// feed nay tu lop hoc, va minh la nguoi tao ra lop hoc
                    || (existingFeed.PassiveAccountID_u == currentUser.AccountID_u && existingFeed.Type_s == EnumFeedType.PostOnWall.ToString()))
                {
                    if (Feed.DeleteFeed(existingFeed.FeedID_u) == 1)
                    {
                        return "success";
                    }
                }
                else
                {
                    if (FeedForFriend.Delete(existingFeed.FeedID_u, currentUser.AccountID_u) == 1)
                    {
                        return "success";
                    }
                }
            }
            return "unsuccess";
        }

        [RequireUserLogin]
        [HttpPost]
        public string DeleteFeedComment(string feedCommentID)
        {
            Account currentUser = RequireUserLogin.LoginUser;
            FeedComment fcmt = FeedComment.SelectByFeedCommentID(Guid.Parse(feedCommentID));
            if (feedCommentID != null)
            {
                if (fcmt.ActiveAccount_u == currentUser.AccountID_u
                 || fcmt.FeedReference.Value.ActiveAccountID_u == currentUser.AccountID_u
                 || (fcmt.FeedReference.Value.CourseReference.Value != null
                        && fcmt.FeedReference.Value.CourseReference.Value.AccountID_u == currentUser.AccountID_u))
                {
                    if (FeedComment.Delete(Guid.Parse(feedCommentID)) == 1)
                    {
                        return "success";
                    }
                }
            }

            return "unsucess";
        }

        public ActionResult NoAccess()
        {
            return View();
        }

        public ActionResult LeftMainMenu()
        {
            return PartialView("");
        }
    }
}
